#include <iostream>
#include <sys/select.h>
#include <string>
#include <memory>
#include <unistd.h>
#include <functional>
#include "Socket.hpp"
#include "Log.hpp"
#include "translation.hpp"
using namespace std;
// int select(int nfds, fd_set *readfds, fd_set *writefds,
//     fd_set *exceptfds, struct timeval *timeout);

// void FD_CLR(int fd, fd_set *set);
// int  FD_ISSET(int fd, fd_set *set);
// void FD_SET(int fd, fd_set *set);
// void FD_ZERO(fd_set *set);
using func_t = function<string(string &)>;
class TcpServer
{
    const int defaultfd = -1;
    const static int size = sizeof(fd_set) * 8;

public:
    TcpServer(int port)
        : _listensock(make_unique<TcpSocket>()),
          _isrunning(false),
          _func([this](string &input)
                { return _translator.Execute(input); })
    {
        _listensock->BuildTcpSocketMethod(port);
        for (int i = 0; i < size; i++)
            _fd_array[i] = defaultfd;
        _fd_array[0] = _listensock->GetListensockfd();
    }
    void Start()
    {
        _isrunning = true;
        // struct timeval timeout = {1, 0};
        while (_isrunning)
        {
            fd_set rfds;
            FD_ZERO(&rfds);
            int maxfd = -1;
            for (int i = 0; i < size; i++)
            {
                if (_fd_array[i] != defaultfd)
                    FD_SET(_fd_array[i], &rfds);
                if (_fd_array[i] > maxfd)
                    maxfd = _fd_array[i];
            }
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);
            switch (n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "select error";
                break;
            case 0:
                LOG(LogLevel::INFORMATION) << "select timeout";
                break;
            default:
                LOG(LogLevel::DEBUG) << "有事件就绪了..., n : " << n;
                Dispatcher(rfds);
                break;
            }
        }
        _isrunning = false;
    }
    // 链接管理器
    void Accepter()
    {
        INETADDR client;
        int sockfd = _listensock->Accept(&client);
        if (sockfd > 0)
        {
            int i = 0;
            for (; i < size; i++)
            {
                if (_fd_array[i] == defaultfd)
                    break;
            }
            // 说明辅助数组_fd_array[]已满
            if (i == size)
            {
                LOG(LogLevel::DEBUG) << " _fd_array[] is full,close sockfd" << sockfd;
                close(sockfd);
            }
            else
            {
                // 添加新链接到辅助数组
                _fd_array[i] = sockfd;
            }
        }
        else
            LOG(LogLevel::INFORMATION) << "accept error";
    }
    // IO处理器
    void Receiver(int index)
    {
        char buffer[1024];
        ssize_t n = recv(_fd_array[index], buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            // cout << "client say@ " << buffer << endl;
            string English = buffer;
            while (!English.empty() &&
                   (English.back() == '\r' || English.back() == '\n'))
            {
                English.pop_back();
            }
            string Chinese = _func(English);
            cout << "client say@ " << Chinese << endl;
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFORMATION) << "clien quit...";
            // 关闭_fd_array[index]
            close(_fd_array[index]);
            // 不要让select在关系这个_fd_array[index]了
            _fd_array[index] = defaultfd;
        }
        else
        {
            LOG(LogLevel::ERROR) << "recv error";
            // 关闭_fd_array[index]
            close(_fd_array[index]);
            // 不要让select在关系这个_fd_array[index]了
            _fd_array[index] = defaultfd;
        }
    }
    // 事件派发器
    void Dispatcher(fd_set &rfds)
    {
        // 需要确定是有新链接到来还是普通sockfd有数据可读
        for (int i = 0; i < size; i++)
        {
            // 说明fd合法
            if (_fd_array[i] != defaultfd)
            {
                // 说明fd合法且就绪
                if (FD_ISSET(_fd_array[i], &rfds))
                {
                    // 新链接到来
                    if (_fd_array[i] == _listensock->GetListensockfd())
                    {
                        Accepter();
                    }
                    // 说明普通文件描述符有数据可读
                    else
                    {
                        Receiver(i);
                    }
                }
            }
        }
    }
    void Stop()
    {
        _isrunning = false;
    }

    ~TcpServer() {}

private:
    unique_ptr<Socket> _listensock;
    bool _isrunning;
    int _fd_array[size];
    Translation _translator;
    func_t _func;
};